//
//  CombinedPunchViewController.m
//  YuTang
//
//  Created by 葛悦彣 on 2025/3/10.
//

#import "CombinedPunchViewController.h"
#import "TimeFrameShowView.h"
#import "CombinedPunchTableViewCell.h"
#import "getPondTissueListModel.h"
#import "DTChoosePersonListShowView.h"

#import "YTSelectStringShowView.h"
@interface CombinedPunchViewController ()

@property (nonatomic ,strong) UILabel * leftLab;
@property (nonatomic ,strong) UILabel * rightLab;
///结束时间
@property (nonatomic ,strong) NSString * executeEndTime;
///开始时间
@property (nonatomic ,strong) NSString * executeStartTime;
///塘口ID
@property (nonatomic ,strong) NSString * pondId;
///选中多少
@property (nonatomic ,strong) UILabel * seledContLab;

@property (nonatomic ,strong) CombinedPunchALLModel * model;
@property (nonatomic ,strong)  UIButton * qrbtn;

@end

@implementation CombinedPunchViewController
- (CombinedPunchALLModel *)model{
    if(!_model){
        _model = [CombinedPunchALLModel new];
        _model.OldTissueName = self.tissueName;
        _model.pondNameList = self.pondNameList;
    }
    return _model;
}

- (NSString *)executeEndTime {
    if(!_executeEndTime){
        _executeEndTime = @"23:59";
    }
    return _executeEndTime;
}
- (NSString *)executeStartTime {
    if(!_executeStartTime){
        _executeStartTime = @"00:00";
    }
    return _executeStartTime;
}
- (NSString *)pondId {
    if(!_pondId){
        _pondId = @"";
    }
    return _pondId;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupView];
    // Do any additional setup after loading the view.
}
- (void)setupView{
//    self.NoDataHidden = YES;
    self.shutDownBack = YES;
    
    UIView * topview = [UIView new];
    topview.backgroundColor = KcolorHex(@"#0967FF");
    [self.view addSubview:topview];
    [topview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.height.offset(Knav_HeightX);
    }];
    MJWeakSelf
    UIView * backview = [UIView new].addClickBlock(^{
        [weakSelf popViewController];
    });
    [topview addSubview:backview];
    [backview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(44);
        make.left.bottom.offset(0);
        make.width.offset(kwt(120));
    }];
    
    UIImageView * leftimg = kimageView(@"white_path");
    [backview addSubview:leftimg];
    [leftimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(20);
        make.left.offset(kwt(10));
        make.centerY.offset(0);
    }];
    
    UILabel * leftlab = [DTKTool labelWithText:@"合并打卡" andFont:kCFont(18) andTextColor:UIColor.whiteColor];
    [backview addSubview:leftlab];
    [leftlab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(43));
        make.centerY.offset(0);
    }];
    
    UIView * btnview = [UIView new];
    btnview.backgroundColor = KcolorHex(@"#ECEDEE");
    [self.view addSubview:btnview];
    [btnview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.equalTo(topview.mas_bottom);
        make.height.offset(kwt(53));
    }];
    
    UIView * leftview = [UIView new];
    leftview.addClickBlock(^{
        [DayTimeFrameShowView CZshowviewWithTitle:@"设置时间段" andStartTime:weakSelf.executeStartTime andEndTime:weakSelf.executeEndTime andRightBlock:^(NSString * _Nonnull StartTime, NSString * _Nonnull EndTime) {
            weakSelf.executeStartTime = StartTime;
            weakSelf.executeEndTime = EndTime;
            weakSelf.leftLab.text = [NSString stringWithFormat:@"%@~%@",weakSelf.executeStartTime,weakSelf.executeEndTime];
            [weakSelf loadNewData];
        } andCZBlock:^{
            weakSelf.executeStartTime = nil;
            weakSelf.executeEndTime = nil;
            weakSelf.leftLab.text = [NSString stringWithFormat:@"%@~%@",weakSelf.executeStartTime,weakSelf.executeEndTime];
            [weakSelf loadNewData];
        }];
    });
    leftview.backgroundColor = UIColor.whiteColor;
    [DTKTool YJ:kwt(5) andView:leftview];
    [btnview addSubview:leftview];
    [leftview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(8));
        make.top.offset(kwt(10));
        make.width.offset(kwt(172));
        make.height.offset(kwt(37));
    }];
    
    UIImageView * leftImg = kimageView(@"tangkou_expand");
    [leftview addSubview:leftImg];
    [leftImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.right.offset(kwt(-10));
        make.width.height.offset(kwt(15));
    }];
    UILabel * leftLab = [DTKTool labelWithText:[NSString stringWithFormat:@"%@~%@",self.executeStartTime,self.executeEndTime] andFont:kFont(15) andTextColor:KcolorHex(@"#222222")];
    self.leftLab = leftLab;
    [leftview addSubview:leftLab];
    [leftLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.right.offset(kwt(-45));
        make.left.offset(kwt(10));
    }];
    
    UIView * rightview = [UIView new];
    rightview.addClickBlock(^{
        [weakSelf openTKBZ];
    });
    rightview.backgroundColor = UIColor.whiteColor;
    [DTKTool YJ:kwt(5) andView:rightview];
    [btnview addSubview:rightview];
    [rightview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftview.mas_right).offset(kwt(10));
        make.top.offset(kwt(10));
        make.width.offset(kwt(172));
        make.height.offset(kwt(37));
    }];
    
    UIImageView * rightImg = kimageView(@"tangkou_expand");
    [rightview addSubview:rightImg];
    [rightImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.right.offset(kwt(-10));
        make.width.height.offset(kwt(15));
    }];
    UILabel * rightLab = [DTKTool labelWithText:@"编组-全部塘口" andFont:kFont(15) andTextColor:KcolorHex(@"#222222")];
    self.rightLab = rightLab;
    [rightview addSubview:rightLab];
    [rightLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.right.offset(kwt(-45));
        make.left.offset(kwt(10));
    }];
    
    UIView * buttomview = [UIView new];
    buttomview.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:buttomview];
    [buttomview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.offset(0);
        make.height.offset(kwt(63) + KSafeAreaBottomHeight);
    }];
    
    UILabel * templab = [DTKTool labelWithText:@"已选" andFont:kFont(17) andTextColor:KcolorHex(@"#5A6066")];
    [buttomview addSubview:templab];
    [templab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(15));
        make.top.offset(kwt(23));
        make.height.offset(kwt(17));
    }];
    UILabel * seledContLab = [DTKTool labelWithText:@"0" andFont:kFont(17) andTextColor:KcolorHex(@"#0967FF")];
    self.seledContLab = seledContLab;
    [buttomview addSubview:seledContLab];
    [seledContLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(templab.mas_right).offset(kwt(5));
        make.centerY.equalTo(templab);
        make.height.offset(kwt(17));
    }];
    
    UILabel * templab2 = [DTKTool labelWithText:@"项" andFont:kFont(17) andTextColor:KcolorHex(@"#0967FF")];
    [buttomview addSubview:templab2];
    [templab2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(seledContLab.mas_right).offset(kwt(5));
        make.centerY.equalTo(seledContLab);
        make.height.offset(kwt(17));
    }];
    
    UIButton * qrbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.qrbtn = qrbtn;
    qrbtn.backgroundColor = [UIColor gradientColorWithSize:CGSizeMake(kwt(179), 1) direction:GradientColorDirectionLevel startColor:KcolorHex(@"#2892FE") endColor:KcolorHex(@"#0366FE")];
    [qrbtn setTitle:@"去打卡" forState:UIControlStateNormal];
    [qrbtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    qrbtn.titleLabel.font = kCFont(18);
    [DTKTool YJ:kwt(5) andView:qrbtn];
    [qrbtn addTarget:self action:@selector(DKApi) forControlEvents:UIControlEventTouchUpInside];
    [buttomview addSubview:qrbtn];
    [qrbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(kwt(48));
        make.width.offset(kwt(178));
        make.right.offset(kwt(-12));
        make.centerY.equalTo(templab);
    }];
    
    
    [self.view addSubview:self.tableview];
    self.tableview.backgroundColor = KcolorHex(@"#ECEDEE");
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.equalTo(btnview.mas_bottom);
        make.bottom.equalTo(buttomview.mas_top);
    }];
    
    [self loadNewData];
}

- (void)openTKBZ{
    ///选编组和池塘
    [self.view showBusyHUD];
    [SCNetManger PostPondTissueGetPondTissueListWithDict: [NSMutableDictionary dictionary] andCompetionHandlerBlock:^(HTTPArrBase * model) {
        [self.view hideBusyHUD];
        if(model.code ==200){
            NSArray <getPondTissueListModel *>* array = [NSArray yy_modelArrayWithClass:getPondTissueListModel.class json:model.result ];
            NSLog(@"%@",array);
            MJWeakSelf
            [DTChoosePersonListShowView showViewWithArray:array andBlock:^(getPondTissueListModel * _Nonnull pondModel) {
                [weakSelf openTKWithtissueId:pondModel.ID andName:pondModel.TJname];
            } andCZBlock:^{
                
                weakSelf.pondId = @"";
                weakSelf.rightLab.text = @"编组-全部塘口";
                [weakSelf loadNewData];
            }];
        } else {
            [self.view showWarning:model.message];
        }
    }];
}

- (void)openTKWithtissueId:(NSString *)tissueId andName:(NSString *)name{
    [self.view showBusyHUD];
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    [dict setObject:tissueId forKey:@"tissueId"];
    [SCNetManger PostTaskPondListWithDict:dict  andCompetionHandlerBlock:^(HTTPArrBase * model) {
        [self.view hideBusyHUD];
        if(model.code ==200){
            NSArray <getPondTissueListModel *>* array = [NSArray yy_modelArrayWithClass:getPondTissueListModel.class json:model.result ];
            MJWeakSelf
            NSMutableArray * nameArray = [NSMutableArray array];
            for (getPondTissueListModel * tkmodel in array) {
                [nameArray addObject:tkmodel.name];
            }
            [YTSearchStringShowView showViewWithTitle:@"池塘名称" andDateArray:nameArray andBlock:^(NSString * _Nonnull str) {
                for (getPondTissueListModel * tkmodel in array) {
                    if([tkmodel.name isEqualToString:str]){
                        weakSelf.pondId = tkmodel.ID;
                        weakSelf.rightLab.text = [NSString stringWithFormat:@"%@-%@",name,tkmodel.name];
                        [weakSelf loadNewData];
                        return;
                    }
                }
            }];
        } else {
            [self.view showWarning:model.message];
        }
    }];
}

- (void)loadNewData{
    
    
    [self.view showBusyHUD];
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    [dict setObject:self.executeEndTime forKey:@"executeEndTime"];
    [dict setObject:self.executeStartTime forKey:@"executeStartTime"];
    [dict setObject:self.pondId forKey:@"pondId"];
    [dict setObject:self.ID forKey:@"taskId"];
    [SCNetManger PostTaskMergeWithDict:dict andCompetionHandlerBlock:^(HTTPDicBase * model) {
        [self.view hideBusyHUD];
        if(model.code == 200){
            NSArray<CombinedPunchModel *> * array = [NSArray yy_modelArrayWithClass:CombinedPunchModel.class json:model.result];
            NSMutableArray <CombinedPunchModel *>* tempArray = [NSMutableArray array];
            for (CombinedPunchModel * mm in array) {///去重
                if(![mm.ID isEqualToString:self.ID]){
                    [tempArray addObject:mm];
                }
            }
            [self.model AddModelArray:tempArray];
            [self UIreloadData];
        } else {
            [self.view showWarning:model.message];
        }
    }];
    
    
    
}


- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.model.dayArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.model.dayArray[indexPath.row].cellH;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView * view = [UIView new];
    view.clipsToBounds = YES;
    UILabel * lab = [DTKTool labelWithText:@"最多展示近30天任务" andFont:kFont(14) andTextColor:KcolorHex(@"#9C9B9B")];
    [view addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.offset(0);
    }];
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if(self.model.dayArray.count > 0){
        return kwt(50);
    }
    return 0;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    MJWeakSelf
    
    CombinedPunchTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"CombinedPunchTableViewCell"];
    if (cell == nil) {
        cell = [[CombinedPunchTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CombinedPunchTableViewCell"];
    }
    cell.model = self.model.dayArray[indexPath.row];
    cell.updateBlock = ^{
        [weakSelf UIreloadData];
    };
    cell.seledDayBlock = ^(CombinedPunchDayModel * _Nonnull model) {
        if([weakSelf.model AddSeledDayModel:model]){
            [weakSelf UIreloadData];
        } else {
            [weakSelf.view showWarning:@"最多可合并50项"];
        }
    };
    
    cell.seledModelBlock = ^(CombinedPunchModel * _Nonnull model) {
        if(weakSelf.model.SeledCount < 50){
            model.isSeled = YES;
            [weakSelf UIreloadData];
        } else {
            [weakSelf.view showWarning:@"最多可合并50项"];
        }
    };
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell ;
    
}

- (void)UIreloadData {
    [self.tableview reloadData];
    self.seledContLab.text = [NSString stringWithFormat:@"%d",self.model.SeledCount];
    if(self.model.SeledCount > 0){
        self.qrbtn.backgroundColor = [UIColor gradientColorWithSize:CGSizeMake(kwt(179), 1) direction:GradientColorDirectionLevel startColor:KcolorHex(@"#2892FE") endColor:KcolorHex(@"#0366FE")];
    } else {
        self.qrbtn.backgroundColor = [UIColor gradientColorWithSize:CGSizeMake(kwt(179), 1) direction:GradientColorDirectionLevel startColor:KcolorHex(@"#A3B1F9") endColor:KcolorHex(@"#A3B1F9")];
    }
}
///去打卡页面
- (void)DKApi{
    if(self.model.SeledModelArray.count > 0){
        if(self.seledBlock){
            NSMutableArray * strArray = [NSMutableArray array];
            for (NSString * key in [self.model.seledDict allKeys]) {
                NSArray * array = self.model.seledDict[key];
                [strArray addObject: [NSString stringWithFormat:@"%@ (%@)",key,[array componentsJoinedByString:@","]]];
            }
            self.seledBlock(self.model.SeledModelArray,[strArray componentsJoinedByString:@"\n"]);
            [self.navigationController popViewControllerAnimated:YES];
        }
    } else {
        [self.view showWarning:@"请至少选择一项"];
        return;
    }
}
@end
